package org.bpms.service.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.bpms.model.admin.Btype;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 文档类型操作接口
 * @author hupei
 *
 */
public class TypeService {
	
	/**
	 * 保存类型
	 * @param type
	 * @return
	 */
	@Before(Tx.class)
	public Btype saveOrUpdate(Btype type){
		if (null != type.getStr("id")){
			type.update();
		}else{
			type.set("id", UUID.randomUUID().toString().replaceAll("-", ""));
			type.save();
		}
		return type;
	}
	
	/**
	 * 删除类型
	 * @param id
	 */
	@Before(Tx.class)
	public void del(String id){
		Btype type = Btype.me.findById(id);
		if (null != type){
			type.delete();
			Db.update("delete from typeuser where tid=?" , id);
		}
	}
	
	/**
	 * 得到所有的文档类型
	 * @return
	 */
	public List<Btype> allType(){
		return Btype.me.find("select * from btype");
	}
	
	/**
	 * 获取用户拥有的档案类型
	 * @param uid
	 * @return
	 */
	public List<Btype> getTypeFromUser(String uid){
		List<Btype> lb = Btype.me.find("select a.* from btype a , typeuser b "
				+ "where a.id = b.tid and b.uid=?" , uid);
		return lb;
	}
	
	/**
	 * 保存类型用户关系
	 * @param maptree
	 * @param typeId
	 */
	@Before(Tx.class)
	public void updateUserRelation(Map maptree , String typeId){
		if (null != maptree.get("pId") && !maptree.get("id").equals("-1")){
			if ((boolean)maptree.get("checked")){
				List<Record> records = Db.find("select * from typeuser where tid=? and uid=?",
						typeId , maptree.get("id"));
				if (null == records || records.size() == 0){
					Record typeuser = new Record().set("uid", maptree.get("id"))
							.set("tid", typeId);
					Db.save("typeuser", typeuser);
				}
			}else{
				List<Record> records = Db.find("select * from typeuser where tid=? and uid=?",
						typeId , maptree.get("id"));
				if (null != records && records.size() > 0){
					Db.deleteById("typeuser", records.get(0).getInt("id"));
				}
			}
		}
		if (null != maptree.get("children")){
			List list = (ArrayList) maptree.get("children");
			if (null != list && list.size() > 0){
				for (int i = 0 ; i < list.size() ; i++){
					Map temp = (Map)list.get(i);
					if (null != temp){
						updateUserRelation(temp , typeId);
					}
				}				
			}
		}
	}
	
}
